<style lang="scss" scoped>
@import './custom-screening.scss';

.check-item {
  @include checkItem;
}

.checkbox-group {
  height: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
</style>
<template>
  <div class="checkbox-group">
    <button class="ui button mini check-item basic" type="button" @click="checkAll" :disabled="isDisabled">
      <i v-show="isAllChecked" class="x icon" style="color:#bbb"></i>
      <i v-show="!isAllChecked" class="check icon" style="color:#25B7D3"></i>
    </button>
    <button class="ui button mini check-item" type="button" v-for="(item, index) in value" :key="index"
      :class="{ primary: isChecked(item.id), basic: !isChecked(item.id) }" @click="toggleCheck(index)"
      :disabled="isDisabled">
      {{ item.label || item.id }}
    </button>
  </div>
</template>
<script>
export default {
  name: 'screening-checkbox',
  props: {
    value: {
      type: Array,
      default: function () {
        return []
      }
    },
    label: {
      type: String,
      default: ''
    },
    modelId: {
      type: String,
      default: ''
    }
  },
  computed: {
    checkedItems () {
      return this.modelId.split(',')
    },
    isDisabled () {
      return !this.$listeners['update:modelId']
    },
    isAllChecked () {
      return this.value.every(item => {
        return this.modelId.includes(item.id)
      })
    }

  },
  methods: {
    toggleCheck (index) {
      let arr = this.modelId.split(',')
      let currentId = String(this.value[index].id)
      arr.forEach((id, i) => {
        if (currentId && id === currentId) {//反选
          arr.splice(i, 1)
        } else if (i === arr.length - 1) {
          if (id === '') {
            arr[i] = currentId.toString()
          } else {
            arr.push(currentId.toString())
          }
        }
      })

      let ids = arr.toString().replace(/^,/, '').replace(/,$/, '')
      this.update(ids)
    },
    checkAll () {
      if (!this.isAllChecked) {
        let arr = this.value.map((item) => {
          return item.id
        })
        this.update(arr.toString())
      } else {
        this.update('')
      }
    },
    isChecked (id) {
      return this.checkedItems.includes(String(id))
    },
    update (string) {
      this.$emit('update:modelId', string)
      this.$emit('change', string)
    },
    clear () {
      this.update('')
    }
  },
  mounted () {
    this.$eventHub.$on('ui-screening:reset', this.clear)
  },
  beforeDestroy () {
    this.$eventHub.$off('ui-screening:reset', this.clear)
  }
}
</script>
